21

1、建立表

php artisan make:migration create_category_table --create=category

database/migrations/下找到你的迁移文件
建入:

<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categorys', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('parent_id');
            $table->string('code');
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categorys');
    }
}
php artisan migrate

2、建Model 在app/Category.php

php artisan make: model Category -m



<?php
 
namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Category extends Model
{
    public function childCategory() {
        return $this->hasMany('App\Category', 'parent_id', 'id');
    }
 
    public function allChildrenCategorys()
    {
        return $this->childCategory()->with('allChildrenCategorys');
    }
}


3、调用

$categorys = App/Category::with('allChildrenCategorys')->first();

$categorys->allChildrenCategorys; 

$categorys->allChildrenCategorys->first()->allChildrenCategorys;

将树形分类转成数组ID

有朋友问到这个问题我就更新到这了

 $arr = [];
    array_walk_recursive($categories,function ($v, $k) use(&$arr) {
        if($k == 'id')
            $arr[] = $v;
    });

羊爸爸
935 声望41 粉丝

很懒,没什么好写的